import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { UserService } from "./../user.service";

import { CHANGEMOBILESMS } from "./../../shared";
import { lang } from "moment";

interface BindUser {
  code: string;
  state: string;
  mobile: string;
  smsCode: string;
  smsToken: string;
}
@Component({
  selector: "bindMobile",
  templateUrl: "bindMobile.component.html",
  styleUrls: ["bindMobile.component.less"]
})
export class BindMobileComponent implements OnInit {
  @Output() setModal = new EventEmitter();
  errText: string;
  waitTime: number = 0;
  bindUser: BindUser = {
    code: "",
    state: "",
    mobile: "",
    smsCode: "",
    smsToken: ""
  };
  constructor(private userService: UserService) {}

  ngOnInit() {}
  
  sendSmsCode() {
    this.errText = "";
    if (!this.checkInfoValid()) {
      return;
    }
    this.userService.sendSmsCode( `${CHANGEMOBILESMS}`, this.bindUser.mobile).subscribe((data) => {
      if ( data.code !== 0 ) {
        this.errText = data.msg;
      } else {
        this.errText = "";
        this.bindUser.smsToken = data.data.smsToken;
        this.waitTime = 60;
        let t = setInterval(() => {
          this.waitTime--;
          if (this.waitTime <= 0) {
            clearInterval(t);
          }
        }, 1000);
      }
    }, (err) => {
      console.log("sms/otps failed data:", err);
      this.errText = "服务连接失败，请稍后重试！";
    });
  }
  
  binding() {
    if (this.bindUser.mobile && this.bindUser.smsCode && this.bindUser.smsToken) {
      this.errText = "";
      if (!this.checkInfoValid()) {
        return;
      }
      if (!this.smsCodeValidCheck()) {
        return;
      }
      
      if (this.GetQueryString("code") === null && this.GetQueryString("state") === null) {
        this.errText = "系统错误，请稍后重试"
        return;
      }
      
      this.bindUser.code = this.GetQueryString("code");
      this.bindUser.state = this.GetQueryString("state");
  
      this.userService.bindMobile(this.bindUser).subscribe((data) => {
        if (data.code !== 0) {
          this.errText = data.msg;
        } 
        else {
          this.errText = "绑定成功";
          this.changeModal("hide");
          this.userService.setUser();
          console.log("bind failed data:", data);
        }
      }, (err) => {
        console.log("bind failed data:", err);
        this.errText = "服务连接失败，请稍后重试！";
      })
    }
  }

  private checkInfoValid() {
    let val = true;
    // 校验手机号是否可用
    if (!this.bindUser.mobile) {
      this.errText = "手机号码不能为空";
      val = false;
    } else {
      // let fmt = /^\d{11}$/;
      let fmt = /^1[3578]\d{9}$/;
      if (!fmt.test(this.bindUser.mobile)) {
        this.errText = "手机号格式不正确";
        val = false;
      }
    }
    return val;
  }

    // 验证码设定检测
    private smsCodeValidCheck() {
      let val = true;
      if (!this.bindUser.smsCode) {
        this.errText = "验证码不能为空";
        val = false;
      }
      else {
        let fmt = /^[\d\w]{6}$/;
        if (!fmt.test(this.bindUser.smsCode)) {
          this.errText = "验证码不正确";
          val = false;
        }
      }
      return val;
    }

  changeModal(action: string) {
    if (action === "hide" && !this.userService.isToken) {
    } else {
      this.errText = "";
      this.setModal.emit(action);
    }
  }

  private GetQueryString(name:string) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
  }
}